package Dao.Imp;

import Dao.UserFollowDao;
import modal.User;
import modal.UserFollow;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by tan on 2017/8/24.
 * 15:19
 */
@Repository
@Transactional
public class UserFollowDaoImp implements UserFollowDao {
    @Autowired
    SessionFactory sessionFactory;

    public boolean addMyFollow(String username, String roomid) {
        Session session = sessionFactory.getCurrentSession();
        try
        {
            StringBuilder sql = new StringBuilder();
            sql.append("INSERT INTO user_follow (roommaster,roomid,roomname,username)\n" +
                    "SELECT b.username,b.roomid,b.roomname,a.username from person_info as a,room_master as b \n" +
                    "where a.username =? and b.roomid=?");
            Query query = session.createSQLQuery(sql.toString()).setString(0,username).setString(1,roomid);
            if(query.executeUpdate()==1)
            {
                return true;
            }
        }catch (Exception e)
        {
            System.out.println("UserFollowDaoImp\n订阅失败");
            e.printStackTrace();
        }
        return false;
    }

    public boolean deleteMyFollow(String username, String roomid) {
        Session session = sessionFactory.getCurrentSession();

        try
        {
            StringBuilder sql = new StringBuilder();
            sql.append("delete from user_follow where username = ? and roomid =?");
            Query query = session.createSQLQuery(sql.toString()).setString(0,username).setString(1,roomid);
            if(query.executeUpdate()==1)
            {
                return true;
            }
        }catch (Exception e)
        {
            System.err.println("UserFollowDaoImp\n删除失败");
            e.printStackTrace();
        }
        return false;
    }

    public String hasFollow(String username, String roomid) {
        Session session = sessionFactory.getCurrentSession();
        try
        {
            StringBuilder sql = new StringBuilder();
            sql.append("select * from user_follow where username = ? and roomid =?");
            Query query = session.createSQLQuery(sql.toString()).setString(0,username).setString(1,roomid);
            query.setResultTransformer(Transformers.aliasToBean(UserFollow.class));
            if(query.uniqueResult()!=null)
            {
                return "success";
            }
        }catch (Exception e)
        {
            System.err.println("UserFollowDaoImp\n删除失败");
            e.printStackTrace();
        }
        return "error";
    }
}
